package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
public class UserServiceImpl implements UserService {

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS_UNNORMAL = 0;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageResult<UserDO> list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPage(), userDTO.getPageSize());
        List<UserDO> list = userMapper.selectByPage(userDTO);
        Page<UserDO> page = (Page<UserDO>) list;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void save(User user) {
        if (ObjectUtils.isEmpty(user)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString();

        String encryptedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encryptedPassword);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public void delete(List<Integer> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            throw new RuntimeException("参数错误");
        }
        userMapper.deleteByIds(ids);
    }

    @Override
    public UserDO get(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void update(User user) {
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("参数错误");
        }
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public List<UserDO> getUsersByRole(String roleLabel) {
        return userMapper.selectByRoleLabel(roleLabel);
    }

    @Override
    public List<UserDO> getUsersByDept(Integer deptId) {
        return userMapper.selectByDeptId(deptId);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.selectByUsername(dto);
        if (ObjectUtils.isEmpty(dbUser)) {
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        if (!ObjectUtil.equals(encryptedPassword, dbUser.getPassword())) {
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        if (ObjectUtil.equals(USER_STATUS_UNNORMAL, dbUser.getStatus())) {
            CommonException.throwCommonException(ParamEnum.LOGIN_STATUS_ERROR);
        }
        Role role = roleMapper.selectById(dbUser.getRoleId());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        String jwt = JwtUtils.generateToken(claims);
        return UserLoginVO.<UserLoginVO>builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                //TODO token 未处理
                .token(jwt)
                .build();
    }
}
